<?php
namespace app\admin\controller\soft;
use app\providers\BaseController;
use app\admin\model\SystemUser as SystemUserModel;
use app\admin\model\SystemGroup;
use app\admin\model\SystemUpload;
use app\admin\model\SystemNav;
use app\admin\model\SystemNavAction;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("系统用户")
 * @Apidoc\Group("base")
 * @Apidoc\Sort(2)
 */
class SystemUser extends BaseController
{
	
	/**
    * 修改密码
    *  @Apidoc\Desc("修改当前用户密码")
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/updatePwd")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("password", require=true,default="",desc="原密码" )
    * @Apidoc\Param("newPwd", require=true, default="",desc="新密码" )
    */
	public function updatePwd($password,$newPwd){
		if( empty($password) )
			throw new \think\Exception('原密码不能为空');
		if( empty($newPwd) )
			throw new \think\Exception('新密码不能为空');
		
		$password = md5( 'wei'.md5( $password ) );
		$newPwd = md5( 'wei'.md5( $newPwd ) );

		if(  request()->userInfo['user_pwd'] != $password )
			return \Api::ReError("原密码不正确！");

		$result = (new SystemUserModel)->updatePwd( request()->userInfo['user_id'] , $newPwd);
		if( $result ) {
			return \Api::ReSucess($result, "密码更新成功,请退出重新登录");
		}
		
		return \Api::ReError("密码更新失败，请重试！");
	}
	
	
	/**
    * 修改指定用户密码
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/updateUserPwd")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("user_id", require=true,default="",desc="用户id" )
    * @Apidoc\Param("newPwd", require=true, default="",desc="新密码" )
    */
	public function updateUserPwd($user_id,$newPwd){
		if( empty($newPwd) )
			throw new \think\Exception('新密码不能为空');
		
		$newPwd = md5( 'wei'.md5( $newPwd ) );

		$result = (new SystemUserModel)->updatePwd( $user_id , $newPwd);
		
		if( $result ) {
			return \Api::ReSucess($result, "密码更新成功,请退出重新登录");
		}
		
		return \Api::ReError("密码更新失败，请重试！");
	}
	
	/**
    * 添加用户
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/addUser")
    * @Apidoc\Method("POST")
    */
	public function addUser(){
		$data = request()->post();
		
		//验证
        $result = $this->validate($data,'SystemUser');
        if ($result !== true) {
           return $this ->  ReError($result);
        }
		
		//保存
		$result = (new SystemUserModel)->addUser( $data );
		if($result == 1) {
			return \Api::ReSucess($result,"新增成功");
		}else{
			return \Api::ReError($result);
		}
	}
	
	/**
    * 启用或禁用
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/setEnable")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("data ", require=true,desc="[{user_id:1,is_enable:1,land_status:0}]")
    */
	public function setEnable($data){
		if( empty($data) )
			throw new \think\Exception('参数不能为空');
		
		$result =  (new SystemUserModel)->updates( $data );
		if(!$result){
			return \Api::ReError("操作失败！");
		}else{
			return \Api::ReSucess($result,"操作成功！");
		}
		
	}
	
	/**
    * 获取组织数据
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/getOrgData")
    * @Apidoc\Method("POST")
    */
	public function getOrgData(){
		$data= array();
		$result =  SystemGroup::where('org_id','not in','2,3,4,5')->select();
		if($result[0]){
			foreach ($result as $key => $value) {
				array_push($data,$value);
			}
		}
		return \Api::ReSucess($data,"操作成功！");
	}
	
	/**
    * 新增或更新组织
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/addOrgData")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("org_id", require=true,desc="组织id")
    * @Apidoc\Param("parent_org_id", require=true,desc="父组织id")
    * @Apidoc\Param("org_name", require=true,desc="组织名称")
    */
	public function addOrgData($org_id='',$parent_org_id,$org_name){
		
		$isExist = (new SystemUserModel)->isExistNode($org_name,$parent_org_id,$org_id);
		if($isExist){
			return \Api::ReError("已存在名为 $org_name 的节点！");
		}	
		
		$result =  (new SystemUserModel)->addOrUptateData($org_id,request()->post());
		if(!$result){
			return \Api::ReError("操作失败！");
		}else{
			return \Api::ReSucess($result,"操作成功！");
		}
		
	}
	
   
   /**
    * 删除组织
    *  @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/deleteOrgData")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("orgIds",require=true,desc="组织id 多个逗号分割")
    */
	public function deleteOrgData($orgIds){
		if( empty($orgIds)  )
			throw new \think\Exception('orgIds参数不能为空');
		
		$result = (new SystemUserModel)->selectOrgUser($orgIds);
		if($result[0]){
			return \Api::ReError("该节点或子节点下存在用户数据，不允许删除！");
		}	
		
		$result = (new SystemGroup)->deleteNode($orgIds);
		if( !$result ){
			return \Api::ReError("删除失败！");
		}else{
			return \Api::ReSucess($result,"删除成功！");
		}
		
	}
	
    /**
    * 组织授权
    * @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/action")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("org_id",require=true,desc="组织id")
    * @Apidoc\Param("actions",require=true,desc="权限")
    */
	public function action($org_id,$actions){
		if( empty($org_id)  )
			throw new \think\Exception('org_id参数不能为空');
		
		if( !(new SystemGroup)->addAction($org_id,$actions) ){
			return \Api::ReError("授权失败！");
		}else{
			return \Api::ReSucess($data,"");
		}
	}
	
	
	/**
    * 获取授权列表
    * @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/getActionList")
    * @Apidoc\Method("POST")
    * @Apidoc\Param("org_id",require=true,desc="组织id")
    */
	public function getActionList($org_id){
		if( empty($org_id)  )
			throw new \think\Exception('org_id参数不能为空');
		
		$orgs =  (new SystemGroup)->where("org_id=%s",$org_id)->select();
		$orgActions = json_decode($orgs[0]["action"],true);
		
		$navs = SystemNav::field('func_code,nav_id,nav_url,nav_name,nav_pid')
			->order('sort asc' )
			->select();
			
		$actions = SystemNavAction::select();
		
		$arr=array();
		$whiteList= ["pageMng/index","setParam/index",'userMng/index',"logMng/index"];
		foreach($navs as $value){
			if($value["nav_pid"]=="0" && !in_array($value["nav_url"],$whiteList)){
				
				//当前授权
				$value['action']=[];
				foreach($actions as $act){
					if($act["nav_id"]==$value['nav_id']){
						if( in_array( $act['action_code'], explode(",",$orgActions[$value['func_code']]))  ){
							$act['check']=true;
						}else{
							$act['check']=false;
						}
						array_push($value['action'],$act);
					}
				}
				
				//字节点
				$value['children']=[];
				foreach($navs as $key => $children){
					if($children["nav_pid"]==$value['nav_id']){
						
						//授权
						$children['action']=array();
						foreach($actions as $acts){
							if($acts["nav_id"]==$children['nav_id']){
								if( in_array($acts['action_code'], explode(",",$orgActions[$children['func_code']])) ){
									$acts['check']=true;
								}else{
									$acts['check']=false;
								}
								array_push($children['action'],$acts);
							}
						}
						
						array_push($value['children'],$children);
					}
				}
				
				array_push($arr,$value);
			}
		}
		
		return \Api::ReSucess($arr,"");
	}
	
   /**
    * 获取个人头像
    * @Apidoc\Author("weifashi")
    * @Apidoc\Url("admin/soft/systemUser/getImg")
    * @Apidoc\Method("All")
    * @Apidoc\Param("user_guid",require=true,desc="用户guid")
    */
	public function getImg($user_guid){
		$img =  (new SystemUpload)->where('file_buss_type','用户信息')
			->where('file_type','头像')
			->where('file_guid',$user_guid)
			->value("file_path");
		if($img){
			return env('APP_HOST').'/'.$img;	
		}else{
			return env('APP_HOST').'/admins/images/user_img.jpg';	
		}
	}
}
